package com.ruoyi.security.elevator.websocket;


import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import com.ruoyi.security.elevator.mqtt.MqttGateway;
import com.ruoyi.security.service.IElevatorSendService;
import com.ruoyi.system.api.enums.ElevatorValue;
import lombok.extern.slf4j.Slf4j;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.enums.ReadyState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Configuration
@EnableScheduling
public class ElevatorAliveTask {

    @Autowired
    private IElevatorSendService sendService;

    @Autowired
    private MqttGateway mqttGateway;
    /**
     * 电梯websocket心跳包定时任务
     *
     */
    @Scheduled(cron = "0/20 * * * * ?")
    private void aliveCheckTask()throws URISyntaxException {
        Map<String, String> params = new HashMap<>();
        params.put("msgType", "THIRDPARTY_SERVER_HEARTBEAT_REQ");
        String request = JSONUtil.toJsonStr(params);
        WebSocketClient socketClient = WebSocketSessionManger.getOnlineDevice(ElevatorValue.WEBSOCKET_URI.toString());
        if (socketClient != null){
            log.info("发送心跳包时间 " + DateUtil.date());
            socketClient.send(request);
            //mqttGateway.sendToMqtt("elevator_realData","发送心跳包时间 " + DateUtil.date());
            //监听如果正常关闭，发送send tag;
        }else {
            log.info("发送心跳包,socketClient is null ");
        }
    }

    /**
     * 电梯websocket 定时重连
     * 定时优化，当前配置每隔1分钟执行一次
     */
    @Scheduled(cron = "0 */30 * * * ?")
    private void checkWebsocketTask() throws URISyntaxException {
        WebSocketClient socketClient = WebSocketSessionManger.getOnlineDevice(ElevatorValue.WEBSOCKET_URI.toString());
        if (socketClient == null){
            socketClient = new ElevatorWebsocketClient(ElevatorValue.WEBSOCKET_URI);
            WebSocketSessionManger.putSession(ElevatorValue.WEBSOCKET_URI.toString(),socketClient);
        }
        if(!socketClient.isOpen()){
            if (socketClient.getReadyState().equals(ReadyState.NOT_YET_CONNECTED)){
                try {
                    socketClient.connect();
                    //sendService.sendGetElevatorRealData("1",socketClient);
                } catch (IllegalStateException e) {
                    log.error("msg is :"+e);
                }
            } else if (socketClient.getReadyState().equals(ReadyState.CLOSING) || socketClient.getReadyState().equals(ReadyState.CLOSED)) {
                socketClient.reconnect();
/*                if(socketClient.isOpen()){

                }*/
            }

        }

    }

}
